<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>排序算法之冒泡排序</title>
  </head>
  <body>
    <script type="text/javascript">
      function swap(arr, i, j) {
        let temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
      }

      function bubbleSort(arr) {
        const len = arr.length;
        for (let i = 0; i < len - 1; i++) {
          for (let j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
              swap(arr, j, j+1);
            }
          }
        }
      }

      // 另一种实现
      // function bubbleSort(arr) {
      //   const len = arr.length;
      //   for (let i = len; i >= 2; i--) {
      //     for (let j = 0; j <= i - 1; j++) {
      //       if (arr[j] > arr[j + 1]) {
      //         swap(arr, j, j+1);
      //       }
      //     }
      //   }
      // }

      const arr = [10, 6, 3, 4, 8, 1, 2];
      bubbleSort(arr)
      console.log(arr);
    </script>
  </body>
</html>
